import React from "react";
import {inject, observer} from 'mobx-react';
import * as mobx from 'mobx';
import {Route, withRouter} from 'react-router-dom';
import {asyncComponent} from 'react-async-component';
import {Accordion, Bubble, Checkbox, Icon, List, Modal, NavBar, Popover, Select, Toast, Tools} from "weaver-mobile";
import {RouteLayout} from "weaver-mobile-page";
import isEmpty from 'lodash/isEmpty';

import DirectionList from "./DirectionList";
import * as commonUtil from "../../util/CommonUtil";
import * as pageTypes from "../../constants/OdocPageType";

import "./style/index";

const ButtonGroup = RouteLayout.ButtonGroup;

const getLabel = Tools.getLabel;
const AgreeItem = Checkbox.AgreeItem;

const coms = {
    SelectDirectionList: asyncComponent({
        resolve: () => import('./SelectDirectionList')
    }),
    SaveDirectionModal: asyncComponent({
        resolve: () => import('./SaveDirectionModal')
    }),
}

@withRouter
@inject("odocRequestStore", "odocComsStore")
@observer
export default class Main extends React.Component {
    constructor(props) {
        super(props);

        this.onSubmit = this.onSubmit.bind(this);
        this.onSelectPopOver = this.onSelectPopOver.bind(this);

        const {location, odocRequestStore} = this.props;
        const rootRouter = location.pathname;
        odocRequestStore.setMember({rootRouter});
    }

    componentWillUnmount() {
        const {odocRequestStore} = this.props;
        odocRequestStore.resetStore();
    }

    componentWillMount() {
        this.loadData();
    }

    loadData() {
        const {odocRequestStore, odocComsStore} = this.props;
        const {urlParams = {}} = odocComsStore;
        const {dataId} = urlParams;

        let {requestParam = {}} = odocComsStore;
        requestParam = mobx.toJS(requestParam);
        delete requestParam.markInfo;

        const params = {dataId, ...requestParam};

        //加载数据
        odocRequestStore.loadData(params);
    }

    showSelectList() {
        const {odocRequestStore, odocComsStore} = this.props;
        let {requestParam = {}} = odocComsStore;
        requestParam = mobx.toJS(requestParam);
        delete requestParam.markInfo;

        odocRequestStore.resetListStore();
        odocRequestStore.getTableList({...requestParam});

        const {rootRouter} = odocRequestStore

        window.historyRoute.push({
            pathname: `${rootRouter}/odoc_select_list`,
            callback: this.setSelectDirection.bind(this)
        });
    }

    //从常用去向导入后，根据选择的去向加载数据
    setSelectDirection(dataId) {
        const {odocComsStore, odocRequestStore} = this.props;
        const {urlParams, requestParam = {}} = odocComsStore;
        delete requestParam.markInfo;
        const params = {dataId, ...requestParam};

        //加载数据
        odocRequestStore.importData(params, () => {
            Bubble.success(getLabel(503625, "操作成功！"), 1);
        });
    }


    //取消
    onCancel() {
        const {odocComsStore} = this.props;
        const {onClose} = odocComsStore;
        window.historyRoute.go(-1);

        onClose && typeof onClose == "function" && onClose();
    }

    onSubmit() {
        const {odocComsStore, odocRequestStore} = this.props;
        let {requestParam, submitCallBack: callback} = odocComsStore;
        requestParam = mobx.toJS(requestParam);
        const {workflowid} = requestParam;
        delete requestParam.markInfo;

        let {btnforbiden, isend, nodeOperatorMap} = odocRequestStore;
        const nextDirections = odocRequestStore.getNextDirections();        //存储选中的节点
        nodeOperatorMap = mobx.toJS(nodeOperatorMap);       //存储每个节点设置的操作者

        if (btnforbiden) {      //重复提交
            return;
        }

        const userNames = [];
        const userIdset = new Set();
        const nodeIdSet = new Set();
        let hasArchive = false;         //选择的节点是否包含归档节点
        let archiveNodeName = "";

        const cssText = {
            "margin": "0 5px",
            "fontWeight": "bold",
            "color": "#2db7f5"
        };

        if (isEmpty(nodeOperatorMap) || nextDirections.length <= 0) {
            Bubble.error(getLabel(523407,"请至少设置1个环节的操作人员！"), 2);
            return;
        } else {
            //必填验证
            const checkFail = nextDirections.some(item => {
                const {userList = [], nodeid: nid, nodename: nname, nodetype} = item;
                if (userList.length > 0) {
                    nodeIdSet.add(nid);

                    if (nodetype == 3) {        //归档节点
                        hasArchive = true;
                        archiveNodeName = nname;
                    }

                    userList.forEach(item2 => {
                        const {id: uid, name: uname, lastname: uname2, nodeId: nid} = item2;

                        if (!userIdset.has(uid)) {
                            userIdset.add(uid);
                            userNames.push(uname || uname2);
                        }
                    });
                }

                if (userList.length <= 0) {
                    let errormsg = getLabel(523409, "请添加流转环节$nodename的操作人员");
					const cssTextstr = "margin:0 5px;font-weight:bold;color:#2db7f5";
					errormsg = errormsg.replace(/\$nodename/ig, `<span style="${cssTextstr}">${nname}</span>`);
                    Bubble.error(<span dangerouslySetInnerHTML={{  __html: errormsg}}/>, 3);
                }

                return userList.length <= 0;
            });

            if (checkFail) {
                return;
            }
        }


        //说明除了选择归档节点，还选择了其他节点
        if (hasArchive && nodeIdSet.size > 1) {
            const cmsg = [<span style={cssText}>{archiveNodeName}</span>, <span>{getLabel(523408, "是归档环节，不能与其他环节同时流转，请重新选择！")}</span>];
            Bubble.error(cmsg, 3);
            return;
        }

        odocRequestStore.setMember({workflowid, btnforbiden: true});

        //const params = {requestid, workflowid, nodeid};
        const params = {...requestParam};

        //回调方法
        const submitBack = (data) => {
            const {success = 0, msg = ""} = data;

            if (success == 1) {     //单个提交
                Bubble.success(<span dangerouslySetInnerHTML={{__html: msg}}/>, 2);

                this.onCancel();
                window.setTimeout(() => {
                    callback && callback(isend, data);
                }, 100);
            } else if (success == 2) {      //批量提交
                const {successList} = data;
                odocRequestStore.resetStore();
                window.setTimeout(() => {
                    callback && callback(isend, data);
                }, 100);
            } else {
                Bubble.error(<span dangerouslySetInnerHTML={{__html: msg}}/>, 2);
                odocRequestStore.setMember({btnforbiden: false});
            }
        };

        let confirmMsg0 = getLabel(513015, "确认将文件发送给$username处理？");

        //存在归档节点
        if (hasArchive) {
            confirmMsg0 = getLabel(519033, "确认将文件送阅给$username，并将流程归档？");
        }

        const confirmMsg = this.transformConfirmMsg(confirmMsg0, userNames, cssText);

        commonUtil.showConfirm({
            content: confirmMsg,
            okEvent: () => {
                odocRequestStore.flowNext(params, submitBack);
            },
            cancelEvent: () => {
                odocRequestStore.setMember({btnforbiden: false});
            }
        });
    }


    transformConfirmMsg(cfmMsg, userNames, cssText) {
        const fontCss = {"fontSize": "18px"};

        let nameStr = "";
        let allNames = "";
        if (userNames.length > 10) {
            allNames = userNames.join(", ");
            nameStr = userNames.slice(0, 10).join(", ") + "...";
        } else {
            nameStr = userNames.join(", ");
        }

        const findex = cfmMsg.indexOf("$username");
        const lindex = findex + 9;   //9是$username这几个字符的长度

        const fmsg = cfmMsg.substring(0, findex);
        const lmsg = cfmMsg.substring(lindex);

        let showNames = "";
        if (allNames.length > 0) {
            showNames = <span style={cssText} title={allNames}>{nameStr}</span>
        } else {
            showNames = <span style={cssText}>{nameStr}</span>;
        }

        const confirmMsg = (
            <span style={fontCss}>
                {fmsg}
                {showNames}
                {lmsg}
            </span>
        );

        return confirmMsg;
    }

    openDirectionDialog() {
        const {odocRequestStore} = this.props;

        let {nodeOperatorMap = {}} = odocRequestStore;
        const nextDirections = odocRequestStore.getNextDirections();    //存储选中的节点
        nodeOperatorMap = mobx.toJS(nodeOperatorMap);       //存储每个节点设置的操作者

        if (isEmpty(nodeOperatorMap) || nextDirections.length <= 0) {
            Bubble.error(getLabel(523407,"请至少设置1个环节的操作人员！"), 2);
            return;
        }

        odocRequestStore.setModalVisible(pageTypes.USUAL_DIRECTION_DIALOG, true);
    }

    onSelectPopOver(node, index) {
        const {key} = node;
        if (key == "importDirection") {       //选择常用去向
            this.showSelectList();
        } else if (key == "saveDirection") {       //设为常用去向
            this.openDirectionDialog();
        }

        const {odocRequestStore} = this.props;
        const popoverVisiable = false;
        odocRequestStore.setMember({popoverVisiable});
    }

    generateRouteLayout() {
        const {odocRequestStore} = this.props;
        const {rootRouter} = odocRequestStore;

        const routeMap = {
            odoc_select_list: <coms.SelectDirectionList/>
        };

        const arr = [];
        Object.keys(routeMap).forEach(key => {
            arr.push(
                <Route key={key} path={`${rootRouter}/${key}`} render={() => {
                    return <RouteLayout>
                        <div key={key} className="wm-route-layout">{routeMap[key]}</div>
                    </RouteLayout>
                }}></Route>
            );
        })

        return arr;
    }

    render() {
        const {odocRequestStore} = this.props;

        const buttons = [
            {
                key: 'submit',
                text: getLabel(501196, "确定"),
                onClick: this.onSubmit,
                type: 'primary',
            }
        ];

        const flextStyles = [
            {
                style: {flex: 1}
            }
        ];

        const overlayItem = [];
        const Item = Popover.Item;
        overlayItem.push(<Item key="importDirection">{getLabel(512917, "选择常用去向")}</Item>);
        overlayItem.push(<Item key="saveDirection">{getLabel(512918, "设为常用去向")}</Item>);

        const {popoverVisiable = false, modalVisible, isend} = odocRequestStore;

        const isCheckBoxChecked = isend == "1" ? true : false;

        const popoverCom = <Popover
            mask
            align={{
                overflow: {adjustY: 0, adjustX: 0},
                offset: [-10, 0],
            }}
            visible={popoverVisiable}
            overlay={overlayItem}
            onVisibleChange={v => {
                odocRequestStore.setMember({popoverVisiable: v});
            }}
            onSelect={this.onSelectPopOver}
        >
            <Icon type="ellipsis"/>
        </Popover>

        return (
            <div className="odoc-request-transfer">
                <NavBar
                    mode="light"
                    rightContent={
                        popoverCom
                    }
                >
                    <div className="title">{getLabel(521993, "请选择流转操作者")}</div>
                </NavBar>
                <DirectionList/>
                <div className="odoc-agree-item">
                    <AgreeItem
                        checked={isCheckBoxChecked}
                        onChange={(obj) => {
                            const {checked = false} = obj.target || {};
                            const isend = checked ? "1" : "0";
                            odocRequestStore.setMember({isend});
                        }}>
                        {getLabel(507363, "结束本人处理")}
                    </AgreeItem>
                </div>
                <ButtonGroup data={buttons} flexStyles={flextStyles}/>

                {this.generateRouteLayout()}

                {
                    modalVisible.has(pageTypes.USUAL_DIRECTION_DIALOG) && <coms.SaveDirectionModal/>
                }
            </div>
        );
    }
}